"use strict";
/// <reference path="../Function.js" />

function main() {
    // 获取WebGL上下文
    const gl = getNewCanvasGLContent();
    if (!gl) return;
    gl.enable(gl.CULL_FACE);

    //  顶点着色器
    const vertexCode = `
    // 声明接受顶点位置数据
    attribute vec2 a_position;
    void main(){
        gl_Position = vec4(a_position, 0, 1);
    }
    `;
    const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexCode);
    const posAry = [
        0, 0,
        0.7, 0,
        0, 0.5,
        0.7, 0.5
    ];
    // 绑定顶点缓冲
    const vertexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(posAry), gl.STATIC_DRAW);

    // 两个三角形顶点序号数组
    const idxAry = [
        0, 1, 2,
        2, 1, 3
    ];
    // 绑定索引缓冲
    const idxBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(idxAry), gl.STATIC_DRAW);

    // 片元着色器
    const fragmentCode = `
    precision mediump float;
    // 全局变量
    uniform vec4 u_color;
    void main(){
        gl_FragColor = u_color;
    }
    `;
    const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentCode);

    const program = createProgram(gl, vertexShader, fragmentShader);

    // 设置视口
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    // 清除画布颜色，并设置画布颜色
    gl.clearColor(0.7, 0.7, 0.7, 1);
    // 清除颜色缓冲
    gl.clear(gl.COLOR_BUFFER_BIT);

    // 启用着色程序
    gl.useProgram(program);

    // 获取顶点属性索引位置
    const attrLocatioIdx = gl.getAttribLocation(program, "a_position");
    gl.enableVertexAttribArray(attrLocatioIdx);
    // 重新绑定顶点到缓冲
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.vertexAttribPointer(attrLocatioIdx, 2, gl.FLOAT, false, 0, 0);

    // 颜色属性索引
    const colorLocationIdx = gl.getUniformLocation(program, "u_color");
    gl.uniform4f(colorLocationIdx, Math.random(), Math.random(), Math.random(), 1.0);

    // 绘制2个三角形
    gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
}

main();
